package com.ruoyi.web.controller.cs;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.CheckSwitch;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.ResponsePageInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.cs.domain.TNotice;
import com.ruoyi.cs.domain.dto.pay.RechargeVo;
import com.ruoyi.cs.domain.vo.PersonalBillVo;
import com.ruoyi.cs.domain.vo.SomisspayVo;
import com.ruoyi.cs.domain.vo.TRechargeCountVo;
import com.ruoyi.cs.domain.vo.TRechargeVo;
import com.ruoyi.cs.service.*;
import com.ruoyi.cs.service.payment.SanjinService;
import com.ruoyi.cs.service.payment.YukuaiqiService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import io.swagger.annotations.*;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.cs.domain.TRecharge;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 充值记录Controller
 *
 * @author ruoyi
 * @date 2021-03-25
 */
@RestController
@RequestMapping("/cs/recharge")
@Api(tags = {" 充值记录管理"})
@SuppressWarnings("all")
public class TRechargeController extends BasicsController
{
    private static final Logger log = LoggerFactory.getLogger(TRechargeController.class);
    @Autowired
    private ITRechargeService tRechargeService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private IHCPayService ihcPayService;
    @Autowired
    private ICHPayService ichPayService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Autowired
    private IBHLPayService ibhlPayService;
    @Autowired
    private IFUXINPayService fuxinPayService;
    @Autowired
    private IJiuJiaPayService jiuJiaPayService;
    @Autowired
    private IYouMiYunPayService youMiYunPayService;
    @Autowired
    private YukuaiqiService yukuaiqiService;
    @Autowired
    private SanjinService sanjinService;

    /**
     * 统计金额、利润
     * 条件：时间段、手机号、昵称
     */
    @ApiOperation("统计金额、利润")
    @RequestMapping(name="统计金额、利润",value="countTRechargeTotal",method = RequestMethod.POST)
    public Response<Map<String, BigDecimal>> countTRechargeTotal(@RequestBody TRechargeVo tRechargeVo)
    {
        Map<String, BigDecimal> map = tRechargeService.countTRechargeTotal(tRechargeVo);
        return Response.success(map);
    }

    /**
     * 后台充值列表
     */
    @ApiOperation("后台充值列表")
    @RequestMapping(name="后台充值列表",value="listBack",method = RequestMethod.POST)
    public ResponsePageInfo<TRechargeVo> listBack(@RequestBody TRechargeVo tRechargeVo)
    {
        startPage(tRechargeVo.getPageNum(),tRechargeVo.getPageSize());
        List<TRechargeVo> list = tRechargeService.listBackCount(tRechargeVo);
        return toResponsePageInfo(list);
    }


    @PostMapping("/payjsNotifySomisspay")
    @Log(title = "充值异步回调", businessType = BusinessType.INSERT)
    public Object payjsNotifySomisspay(SomisspayVo notifyDTO) {
        try {
            log.info("聚合异步通知调用:{}", notifyDTO);
            return tRechargeService.payjsNotifySomisspay(notifyDTO);
        } catch (Exception e) {
            log.error("用户聚合充值异步通知异常:{},参数:{}", e.getMessage(), notifyDTO.toString());
            return "failure";
        }
    }

    /**-----------------------------------------前端接口-------------------------------*/
    /**
     * 充值接口
     * @param czMoney
     * @return
     */
    @CheckSwitch
    @ApiOperation("web端充值接口")
    @RequestMapping(name="充值接口",value="rechargeSomisspay",method = RequestMethod.GET)
    @Log(title = "充值接口", businessType = BusinessType.INSERT)
    public Response<Map> rechargeSomisspay(
           @RequestParam(name = "czMoney",required = true) int czMoney,
           @RequestParam(name = "czEquipment",required = true) String czEquipment,
           @RequestParam(name = "czType",required = true) String czType){
        try {
            String userId = tokenService.getLoginUserId();
//            SysConfig czMoneyRangeConfig = sysConfigMapper.checkConfigKeyUnique("cz_money_range");
//            String czmonerange = czMoneyRangeConfig.getConfigValue();
//            String[] range = czmonerange.split("-");
//            int min = Integer.parseInt(range[0]);
//            int max = Integer.parseInt(range[1]);
//            if(czMoney<min || czMoney>max){
//                return Response.fail("充值金额必须在["+min+"-"+max+"]区间");
//            }

            SysConfig czplatformConfig = sysConfigMapper.checkConfigKeyUnique("recharge_platform");
            String czplatform = StringUtils.isEmpty(czplatformConfig.getConfigValue()) ? "0" : czplatformConfig.getConfigValue();
            BigDecimal czfee = BigDecimal.valueOf(czMoney);
//            if (Constants.CZPLATFORM0.equals(czplatform)) {
//                /**聚合支付*/
//                return tRechargeService.rechargeSomisspay(userId,czfee, czEquipment);
//            } else if (Constants.CZPLATFORM1.equals(czplatform)) {
//                /**汇潮支付*/
//                return ihcPayService.recharge(userId,czfee,czEquipment);
//            }else if(Constants.CZPLATFORM2.equals(czplatform)){
//                /**传化支付*/
//                return ichPayService.chRecharge(userId,czfee,czEquipment);
//            }else if (Constants.CZPLATFORM3.equals(czplatform)){
//                /**宝和利支付*/
//                return ibhlPayService.bhlRecharge(userId,czfee,czEquipment);
//            }else if (Constants.CZPLATFORM4.equals(czplatform)){
//                /**富信支付*/
//                return fuxinPayService.recharge(userId,czfee,czEquipment,czType);
//            }else if(Constants.CZPLATFORM5.equals(czplatform)){
//                /**九嘉支付*/
//                return jiuJiaPayService.recharge(userId,czfee,czEquipment);
//            }else if(Constants.CZPLATFORM6.equals(czplatform)){
//                /**优米云支付*/
//                return youMiYunPayService.recharge(userId,czfee,czEquipment);
//            }else
//
                if(Constants.CZPLATFORM7.equals(czplatform)){
                /**you*/
                return yukuaiqiService.recharge(userId,czfee,czEquipment);
            }else if(Constants.CZPLATFORM8.equals(czplatform)){
                /**三斤支付*/
                return sanjinService.recharge(userId,czfee,czEquipment,czType);
            }
            else {
                return Response.fail("无对应充值方式");
            }

        } catch (Exception e) {
            log.error("充值接口异常:{}",e.getMessage());
            return Response.fail("系统繁忙，请稍候再试!");
        }
    }


    /**
     * 充值接口
     * @param czMoney
     * @return
     */
    @CheckSwitch
    @ApiOperation("web端充值接口_动态传支付")
    @PostMapping("rechargeDynamic")
    @Log(title = "动态支付充值接口", businessType = BusinessType.INSERT)
    public Response<Map> rechargeDynamic(@Validated @RequestBody RechargeVo vo){
        try {
            SysConfig czMoneyRangeConfig = sysConfigMapper.checkConfigKeyUnique("cz_money_range");
            String czmonerange = czMoneyRangeConfig.getConfigValue();
            String[] range = czmonerange.split("-");
            int min = Integer.parseInt(range[0]);
            int max = Integer.parseInt(range[1]);
            if(vo.getCzMoney()<min || vo.getCzMoney()>max){
                return Response.fail("充值金额必须在["+min+"-"+max+"]区间");
            }

             String userId = tokenService.getLoginUserId();
             String czplatform = vo.getCzplatform();
             if(Constants.CZPLATFORM7.equals(czplatform)){
                /**yukuaiqi支付*/
                return yukuaiqiService.recharge(userId,BigDecimal.valueOf(vo.getCzMoney()),vo.getCzEquipment());
            }else if(Constants.CZPLATFORM8.equals(czplatform)){
                /**三斤支付*/
                return sanjinService.recharge(userId,BigDecimal.valueOf(vo.getCzMoney()),vo.getCzEquipment(),vo.getCzType());
            }
            else {
                return Response.fail("无对应充值方式");
            }

        } catch (Exception e) {
            log.error("动态支付充值接口异常:{}",e.getMessage());
            return Response.fail("系统繁忙，请稍候再试!");
        }
    }

    /**
     * 获取充值记录详细信息
     */
    @ApiOperation("web端获取充值记录详细信息")
    @RequestMapping(name="获取充值记录详细信息",value="getInfo",method = RequestMethod.GET)
    @ApiImplicitParam(name = "czId",value = "充值记录ID" ,dataType = "String", paramType = "query", required = false)
    public Response<TRecharge> getInfo(String czId)
    {
        return Response.success(tRechargeService.selectTRechargeById(czId));
    }


    /**
     * 获取充值记录详细信息
     */
    @ApiOperation("web端查询个人充值账单")
    @RequestMapping(name="查询个人充值账单",value="getPersonalBill",method = RequestMethod.POST)
    public ResponsePageInfo<PersonalBillVo> getPersonalBill(@RequestBody PersonalBillVo personalBillVo)
    {
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        if(loginUser == null){
            ResponsePageInfo re = new ResponsePageInfo();
            re.setMsg("请刷新后重试！");
            re.setCode(Constants.FAILCODE);
            return re;
        }
        SysUser sysUser = loginUser.getUser();
        String userId = sysUser.getLoginUserId();
        startPage(personalBillVo.getPageNum(),personalBillVo.getPageSize());
        personalBillVo.setUserId(userId);
        List<PersonalBillVo>  personalBillList = tRechargeService.getPersonalBill(personalBillVo);
        return toResponsePageInfo(personalBillList);
    }
}
